/*  
 * cafe-select.js
 * @Author :      PANRUSEN
 * @CreateDate :  2017年6月20日
 * Copyright (c) 2017, NRIET.　
 * TODO
 * 		下拉输入框组件
 */

;define(function(call){
	
	var $curSel = $('div.cafe-select');
	
	function _getNode(){
		
	}
	
	function _getStatus(){
		
	}
	
	function _events(node){
		if(!(node.length > 0)) return;
		
		var $input = $(node).find('input.cafe-select-text'),
			$ico = $(node).find('span.cafe-select-icon'),
			$menu = $(node).find('ul.cafe-select-menu'),
			$menuli = $menu.find('li'),
			valarr = [];
		if($menuli.length > 0){
			$.each($menuli, function(index, li){
				valarr.push({
					id: $(li).data('key'),
					name: $(li).data('name')
				});
			});
		}
		
		var attrobj = {
				isopen: $(node).data('status'),
				disable: $(node).data('disable'),
				inputable: $(node).data('inputable'),
				autocomplete: $(node).data('autocomplete'),
		};
		
		$input.attr({
			disabled: attrobj.disable? true: false,
			readonly: !attrobj.inputable? true: false
		});
		
		$input.off('focusin').on('focusin', function(e){
			e.stopPropagation();
			$(node).attr({'data-status': 'open'}).data('status', 'open');
		}).off('keyup').on('keyup', function(e){
			e.stopPropagation();
			var reg = new RegExp($(this).val());
			if(attrobj.autocomplete && attrobj.inputable && !attrobj.disable){
				$.each($menuli, function(index, li){
					var nm = $(li).data('name');
					if(reg.test(nm)){
						 $(li).show();
					} else {
						 $(li).hide();
					}
			});
			}
		});
		$(window.document.body).off('mousedown').on('mousedown', function(e){
			if(!e) e = window.event;
			e.stopPropagation();
			var tag = e.target, tnm = tag.tagName, ptag = tag.parentNode;
			if($(ptag).hasClass('cafe-select-menu') && tnm.toLocaleUpperCase() === 'LI'){
				var $zs = $(tag);
				var obj = {
						id: $zs.data('key'),
						name: $zs.data('name')
				};
				$input.val($zs.data('name'));
				$input.attr({
					'data-val':obj,
					'value': $zs.data('name')
				}).data('val', obj);
			}
			var status = $(tag).hasClass('cafe-select-text')? 'open': 'off';
			$(node).attr({'data-status': status}).data('status', status);
			if(status === 'off'){
				$menuli.show();
			}
		});
		
	}
	
	function _setConfig(cfs){
		
	}
	
	var obj = {
			cursel: $curSel,
			getnode: _getNode,
			getstatus: _getStatus,
			events: _events,
			initcfgs: _setConfig
	}
	
	if(typeof call === 'function'){
		call(obj);
	}
	
}(function(obj){
	
	$.fn.select = function(settings){
		var options = {
				id: null,
				appendTo: null,
				status: 'off',
				disable: false,
				inputable: true,
				autocomplete: true
		};
		this.config = $.extend({
		}, options, settings);
		
		obj.initcfgs(this.config);
		obj.events(this);
	};
	
	if(obj.cursel){
		$(obj.cursel).select();
	}
	
	
}));



